use crate::{biz, model};
use crate::util::Responder;
use crate::request::{UpdateTaskRequest, CreateTaskRequest, PingResponse};

use rbatis::RBatis;
use poem_openapi::{OpenApi, param::Path};
use poem_openapi::payload::Json;
use poem_openapi::param::Query;

pub struct TaskListAPI {
    pub rb: RBatis,
}

// #[poem_grants::open_api]
#[OpenApi]
impl TaskListAPI {
    /// 健康检查
    #[oai(path = "/ping", method = "get")]
    async fn health_check(&self) -> Json<PingResponse> {
        Json(PingResponse {
            ping: "pong".to_string(),
        })
}

    /// 根据id获取task详情
    #[oai(path = "/:id", method = "get")]
    async fn get_task_by_id(&self, id: Path<i64>) -> Responder<model::TaskList> {
        match biz::TaskListBiz::detail(&self.rb, &id).await {
            Ok(resp) => Responder::data(resp),
            Err(err) => Responder::err(err),
        }
    }


    /// 获取task列表(支持分页和标题搜索)
    #[oai(path = "/", method = "get")]
    async fn get_task_list(
        &self,
        page: Query<Option<u64>>,
        page_size: Query<Option<u64>>,
        title: Query<Option<String>>,
    ) -> Responder<Vec<model::TaskList>> {
        match biz::TaskListBiz::list(&self.rb, page.0, page_size.0, title.0).await {
            Ok(list) => Responder::data(list),
            Err(err) => Responder::err(err),
        }
    }

    /// 根据id删除task记录
    #[oai(path = "/:id", method = "delete")]
    async fn delete_task(&self, id: Path<i64>) -> Responder<String> {
        match biz::TaskListBiz::delete(&self.rb, &id).await {
            Ok(_) => Responder::ok(),
            Err(err) => Responder::err(err),
        }
    }

    /// 更新task记录
    #[oai(path = "/", method = "put")]
    async fn update_task(
        &self,
        req: Json<UpdateTaskRequest>,
    ) -> Responder<String> {
        match biz::TaskListBiz::update(
            &self.rb,
            req.0,
        ).await {
            Ok(_) => Responder::ok(),
            Err(err) => Responder::err(err),
        }
    }

    /// 创建task记录
    #[oai(path = "/", method = "post")]
    async fn create_task(
        &self,
        req: Json<CreateTaskRequest>,
    ) -> Responder<model::TaskList> {

        match biz::TaskListBiz::create(&self.rb, req.0).await {
            Ok(resp) => Responder::data(resp),
            Err(err) => Responder::err(err),
        }
    }
}